/**
 * @desc
 * @author  刘贺[of2220]
 * @company qianmi.com
 * @Date    2017/2/10
 */
"use strict";
const promise = require('webutil/promise');

export default class $http{
    static get(url,params={}){
        return promise((resolve, reject) => {
            $.get(url, params)
                .done(success(resolve, reject))
                .fail(fail(reject));
        });
    }

    static post(url,params={}){
        return promise((resolve, reject) => {
            $.post(url, params)
                .done(success(resolve, reject))
                .fail(fail(reject));
        });
    }
}

let success = (resolve, reject) => {
    return (res) => {
        if(typeof(res)=='string') res = JSON.parse(res);
        if (res.result === 'ok') {
            resolve(res);
        } else {
            reject(res);
        }
    };
};

/**
 * ajax fail
 */
let fail = (reject) => {
    return (res) => {
        let msg = '';
        if (res.status === 403) {
            msg = '请求页面资源没有权限禁止访问!';
        } else if (res.status === 404) {
            msg = '请求页面资源不存在!';
        } else if (res.status === 1403) {
            msg = 'session超时，请重新登录.';
        } else {
            msg = '请求发生错误，请检查您的网络，稍后重试!';
        }
        reject(msg);
    };
};